import datetime
import hashlib
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
import uuid

# 自定义用户模型
class User(models.Model):
    username = models.CharField(max_length=64, unique=True)
    password_hash = models.CharField(max_length=128)  # 存储密码的哈希值
    session_token = models.CharField(max_length=64, blank=True)
    is_admin = models.BooleanField(default=False)
    description = models.TextField(blank=True)
    is_banned = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def set_password(self, raw_password):
        """生成密码哈希"""
        self.password_hash = hashlib.sha256(raw_password.encode()).hexdigest()
    
    def check_password(self, raw_password):
        """验证密码"""
        return self.password_hash == hashlib.sha256(raw_password.encode()).hexdigest()
    
    def generate_session_token(self):
        """生成会话令牌"""
        self.session_token = uuid.uuid4().hex
        self.save()
        return self.session_token
    
    def clear_session_token(self):
        """清除会话令牌"""
        self.session_token = ""
        self.save()
    @property
    def password(self):
        """兼容Django密码字段的只读属性"""
        return self.password_hash